﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using LybrixNursingCRMDesktop.FrameWork;
using LybrixNursingCommon;

namespace LybrixNursingCRMDesktop
{
    /// <summary>
    /// Interaction logic for DetailAgent.xaml
    /// </summary>
    public partial class DetailAgent : Page
    {
        
        private readonly LybrixNursingCommon.NursingDBContainer _entities;
        string agentID;
        bool isNew = true;
        agent currentAgent;
        public DetailAgent()
        {
            
            InitializeComponent();
            _entities = Repository.Entities;
            agentID = GetUniqueID();
            ProspectID.Content = agentID;
            isNew = true;
        }
        public DetailAgent(agent _currentAgent)
        {

            InitializeComponent();
            _entities = Repository.Entities;
            currentAgent = _currentAgent;
            InitCusrrentAgent();
            isNew = false;
        }

        private void InitCusrrentAgent()
        {
            FirstName.Text = currentAgent.firstName;
            FamilyName.Text = currentAgent.lastName;
            region.Text = currentAgent.region;
            userName.Text = currentAgent.userName;
            phone1.Text = currentAgent.phone1;
            phone2.Text = currentAgent.phone2;
            password.Password = currentAgent.password;
            ProspectID.Content = currentAgent.agentID;
            ID.Text = currentAgent.socialId;
            isAdmin.IsChecked = currentAgent.isAdmin;
            IsAgent.IsChecked = currentAgent.isAgent;
            IsSuper.IsChecked = currentAgent.isSuperUser;
        }

        private void ToolBar_Loaded(object sender, RoutedEventArgs e)
        {

        }

        private void onSave_Click(object sender, RoutedEventArgs e)
        {

            

            if (!checkmandatoryFields())
                return;
            else
            {
                if (isNew)
                {
                    agent newAgent = new agent();
                    newAgent.firstName = FirstName.GetValue();
                    newAgent.lastName = FamilyName.GetValue();
                    newAgent.socialId = ID.GetValue();
                    newAgent.region = region.GetValue();
                    newAgent.userName = userName.GetValue();
                    newAgent.agentID = agentID;
                    newAgent.phone1 = phone1.GetValue();
                    newAgent.phone2 = phone2.GetValue();
                    newAgent.isAdmin = isAdmin.IsChecked;
                    newAgent.isAgent = IsAgent.IsChecked;
                    newAgent.isSuperUser = IsSuper.IsChecked;
                    newAgent.password = password.Password;
                    _entities.AddToagents(newAgent);
                }
                else
                {
                    currentAgent.firstName = FirstName.GetValue();
                    currentAgent.lastName = FamilyName.GetValue();
                    currentAgent.socialId = ID.GetValue();
                    currentAgent.region = region.GetValue();
                    currentAgent.userName = userName.GetValue();
                    currentAgent.phone1 = phone1.GetValue();
                    currentAgent.phone2 = phone2.GetValue();
                    currentAgent.password = password.Password;
                    currentAgent.isAdmin = isAdmin.IsChecked;
                    currentAgent.isSuperUser = IsSuper.IsChecked;
                    currentAgent.isAgent = IsAgent.IsChecked;
                }

                try
                {
                    
                    _entities.SaveChanges();
                    MessageBox.Show("הרשומה נרשמה בהצלחה","הודעה",MessageBoxButton.OK);
                    NavigationCenter.ShowSearchPage(NavigationTarget.AgentsPage, this);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }

            }
        }

        private string GetUniqueID()
        {
            string tmpID = string.Empty;
            int lastvalue = 1;
            string agentID = string.Empty;
            formula _formula;

            var formulas = (from x in _entities.formulae where x.bo == "AgentFormula" select x);


            if (formulas.Count<formula>() == 0)
            {
                agentID = lastvalue.ToString("0000");
                _formula = new formula();
                _formula.bo = "AgentFormula";
                _formula.lastvalue = 1;
                _entities.AddToformulae(_formula);

            }
            else
            {
                lastvalue = (formulas.First<formula>()).lastvalue;
                _formula = formulas.First<formula>();
                agentID = (lastvalue + 1).ToString("0000");
                _formula.lastvalue = lastvalue +1;
            }


            try
            {
                
                _entities.SaveChanges();
                return "AG" + agentID;
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
                return null ;
            }


           

        }



        private bool checkmandatoryFields()
        {
            bool isValid = true;

            var validationMessage = new StringBuilder();

            //First Name
            if (ValidationFunctions.IsNullEmpty(FirstName.Text))
            {
                FirstName.IsInvalid = true;
                validationMessage.AppendLine(string.Format(FindResource("VLD001").ToString(), FirstName.Tag));
            }
            //Last Name
            if (ValidationFunctions.IsNullEmpty(FamilyName.Text))
            {
                FamilyName.IsInvalid = true;
                validationMessage.AppendLine(string.Format(FindResource("VLD001").ToString(), FamilyName.Tag));
            }
           
            if (validationMessage.Length > 0)
            {
                Messages.ShowWarning(validationMessage.ToString(), MessageBoxButton.OK);
                return false;
            }

            return isValid;
        }

        private void Grid_Scroll(object sender, System.Windows.Controls.Primitives.ScrollEventArgs e)
        {

        }

        private void onDelete_Click(object sender, RoutedEventArgs e)
        {
            IQueryable<Teek> teeks = null;
            MessageBoxResult result = MessageBox.Show("האם אתה בטוח שאתה רוצה למחוק רישימה זו", "אזהרה", MessageBoxButton.YesNo);

            if (result == MessageBoxResult.Yes)
            {
                if (currentAgent != null)
                {

                    teeks =  _entities.Teeks.Where(x => x.agent.Id == currentAgent.Id);
                    if (teeks.Count<Teek>() > 0)
                    {
                        MessageBox.Show("לא תוכל למחוק סוכן זה בגלל שהוא מקושר לרשימות פעילות אחרות.", "אזהרה", MessageBoxButton.OK);
                        return;
                    }
                    else
                    {
                        _entities.DeleteObject(currentAgent);
                        _entities.SaveChanges();
                        NavigationCenter.ShowSearchPage(NavigationTarget.AgentsPage, this);
                    }
                }
            }
        }
    }
}
